package com.example.chapter08;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter08.adapter.CartAdapter;
import com.example.chapter08.database.ShoppingDBHelper;
import com.example.chapter08.entity.CartInfo;
import com.example.chapter08.entity.GoodsInfo;
import com.example.chapter08.util.ToastUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCartActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    private TextView tv_title, tv_count, tv_total_price;
    private LinearLayout ll_empty, ll_content;
    private ListView lv_cart;
    private ShoppingDBHelper mDBHelper;
    // 声明一个购物车中的商品信息列表
    private List<CartInfo> mCartInfoList;
    // 声明一个根据商品编号查找商品信息的映射，把商品信息缓存起来，这样不用每一次都去查询数据库
    private Map<Integer, GoodsInfo> mGoodsMap = new HashMap<>();
    private CartAdapter mCartAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);

        // 购物车页面：返回、清空购物车、结算购物车、进入购物频道
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.btn_clear).setOnClickListener(this);
        findViewById(R.id.btn_settle).setOnClickListener(this);
        findViewById(R.id.btn_shopping_channel).setOnClickListener(this);

        tv_title = findViewById(R.id.tv_title);
        tv_title.setText("购物车");
        lv_cart = findViewById(R.id.lv_cart);
        tv_total_price = findViewById(R.id.tv_total_price);

        tv_count = findViewById(R.id.tv_count);
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));

        ll_empty = findViewById(R.id.ll_empty);
        ll_content = findViewById(R.id.ll_content);

        mDBHelper = ShoppingDBHelper.getInstance(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        showCart();
    }

    // 展示购物车中的商品列表
    private void showCart() {
        // 查询购物车数据库中所有的商品记录
        mCartInfoList = mDBHelper.queryAllCartInfo();
        if (mCartInfoList.size() == 0) {
            return;
        }
        for (CartInfo info : mCartInfoList) {
            // 根据商品编号查询商品数据库中的商品记录
            GoodsInfo goodsInfo = mDBHelper.queryGoodsInfoById(info.goodsId);
            mGoodsMap.put(info.goodsId, goodsInfo);
            info.goodsInfo = goodsInfo;
        }
        mCartAdapter = new CartAdapter(this, mCartInfoList);
        lv_cart.setAdapter(mCartAdapter);
        // 给商品行添加点击事件。点击商品行跳到商品的详情页
        lv_cart.setOnItemClickListener(this);
        // 给商品行添加长按事件。长按商品行就删除该商品
        lv_cart.setOnItemLongClickListener(this);

        // 重新计算购物车中的商品总金额
        refreshTotalPrice();
    }

    private void deleteGoods(CartInfo cartInfo) {
        MyApplication.getInstance().goodsCount -= cartInfo.count;
        // 从购物车的数据库中删除商品
        mDBHelper.deleteCartInfoByGoodsId(cartInfo.goodsId);
        // 从购物车中删除该商品
        CartInfo removedCartInfo = null;
        for (CartInfo info : mCartInfoList) {
            if (info.goodsId == cartInfo.goodsId) {
                removedCartInfo = info;
                break;
            }
        }
        mCartInfoList.remove(removedCartInfo);
        // 显示最新的商品总数
        showCount();
        ToastUtil.show(this, "成功从购物车中删除" + mGoodsMap.get(cartInfo.goodsId).name);
        mGoodsMap.remove(cartInfo.goodsId);
        // 刷新购物车中所有商品的总金额
        refreshTotalPrice();
    }

    // 获取购物车的商品总数，以此决定显示：购物车为空的提示 or 购物车商品列表
    private void showCount() {
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));
        // 购物车中没有商品，显示“空空如也”
        if (MyApplication.getInstance().goodsCount == 0) {
            ll_empty.setVisibility(View.VISIBLE);
            ll_content.setVisibility(View.GONE);
//            lv_cart.removeAllViews();
            // 通知适配器发生了数据变化
            mCartAdapter.notifyDataSetChanged();
        } else {
            ll_content.setVisibility(View.VISIBLE);
            ll_empty.setVisibility(View.GONE);
        }
    }

    // 重新计算购物车中的商品总金额
    private void refreshTotalPrice() {
        int totalPrice = 0;
        for (CartInfo cartInfo : mCartInfoList) {
            GoodsInfo goodsInfo = mGoodsMap.get(cartInfo.goodsId);
            totalPrice += goodsInfo.price * cartInfo.count;
        }
        tv_total_price.setText(String.valueOf(totalPrice));  // tv_total_price 在 ll_content 中
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.btn_shopping_channel) {
            // 从购物车跳转到商场页面
            Intent intent = new Intent(this, ShoppingChannelActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (v.getId() == R.id.btn_clear) {
            // 清空购物车
            mDBHelper.deleteAllCartInfo();
            MyApplication.getInstance().goodsCount = 0;
            showCount();
            ToastUtil.show(this, "成功清空购物车");
        } else if (v.getId() == R.id.btn_settle) {
            // 点击结算按钮
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("结算");
            builder.setMessage("支付功能尚未开通，敬请期待！");
            builder.setPositiveButton("确定", null);
            builder.create().show();
        }
    }

    // 给商品行添加点击事件。点击商品行跳到商品的详情页
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(ShoppingCartActivity.this, ShoppingDetailActivity.class);
        intent.putExtra("goods_id", mCartInfoList.get(position).goodsId);
        startActivity(intent);
    }

    // 给商品行添加长按事件。长按商品行就删除该商品
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        // 给商品行设置长按事件，长按后删除商品
        CartInfo cartInfo = mCartInfoList.get(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
        builder.setMessage("是否从购物车中删除" + cartInfo.goodsInfo.name + "？");
        builder.setPositiveButton("是", (dialog, which) -> {
            // 从集合中移除数据
            mCartInfoList.remove(position);
            // 通知适配器发生了数据变化
            mCartAdapter.notifyDataSetChanged();
            deleteGoods(cartInfo);
        });
        builder.setNegativeButton("否", null);
        builder.create().show();
        return true;
    }
}